package org.waigua.moka.processor;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.HttpException;
import org.apache.log4j.Logger;
import org.waigua.moka.dto.ApiDto;
import org.waigua.moka.exception.CompetitorTimeException;
import org.waigua.moka.exception.SysException;
import org.waigua.moka.service.HttpApiService;
import org.waigua.moka.service.impl.HttpApiServiceImpl;
import org.waigua.moka.util.BigDecimalUtil;

public class CompetitorProcessor
{
	protected Logger log = Logger.getLogger(getClass());
	HttpApiService httpApiService = new HttpApiServiceImpl();

	@SuppressWarnings(
	{ "unchecked", "rawtypes" })
	public void fightCompetitors() throws SysException
	{
		try
		{
			Map<String, ?> competitors = httpApiService.getCompetitors(ApiDto.buildApiDto());
			BigDecimal countDown = BigDecimalUtil.convert(competitors.get("Countdown"));
			if (countDown.compareTo(BigDecimal.ZERO) != 0)
			{
				throw new CompetitorTimeException();
			}
			List<Map> competitorList = (List<Map>) competitors.get("Competitors");
			for (Map<String, ?> c : competitorList)
			{
				if (!(Boolean) c.get("Chip"))
				{
					continue;
				}
				log.info("fight competitors:" + c);
				Map<String, String> params = new HashMap<String, String>();
				params.put("isManual", "0");
				params.put("Competitor", String.valueOf(c.get("Uid")));
				ApiDto apiDto = ApiDto.buildPostContentApiDto(params);
				Map<String, ?> map = httpApiService.freeFight(apiDto);
				log.info("fight competitors result:" + map);
				break;
			}
		}
		catch (HttpException e)
		{
			throw new SysException(e);
		}
		catch (IOException e)
		{
			throw new SysException(e);
		}
	}
}
